<!--登录-->
<template>
  <div class="login-container">
    <div class="login-card">
      <!-- Logo和标题 -->
      <div class="header">
        <div class="logo">
          <img src="@/assets/logo.png" alt="ERP Logo" width="120" height="120" />
        </div>
        <h1 class="title">智能ERP管理系统</h1>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <button
          class="tab-button"
          :class="{ active: loginType === 'account' }"
          @click="switchLoginType('account')"
        >
          账号密码登录
        </button>
        <button
          class="tab-button"
          :class="{ active: loginType === 'phone' }"
          @click="switchLoginType('phone')"
        >
          手机号登录
        </button>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 账号密码登录 -->
        <div v-if="loginType === 'account'" class="form-fields">
          <div class="input-group">
            <div class="input-wrapper">
              <svg class="input-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M10 10C12.7614 10 15 7.76142 15 5C15 2.23858 12.7614 0 10 0C7.23858 0 5 2.23858 5 5C5 7.76142 7.23858 10 10 10Z" fill="#CCCCCC"/>
                <path d="M10 12.5C4.47715 12.5 0 16.9772 0 22.5H20C20 16.9772 15.5228 12.5 10 12.5Z" fill="#CCCCCC"/>
              </svg>
              <input
                type="text"
                placeholder="账号"
                v-model="form.username"
                class="form-input"
              />
            </div>
          </div>
          <div class="input-group">
            <div class="input-wrapper">
              <svg class="input-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">
                <rect x="3" y="8" width="14" height="10" rx="2" fill="#CCCCCC"/>
                <path d="M7 8V6C7 4.34315 8.34315 3 10 3C11.6569 3 13 4.34315 13 6V8" stroke="#CCCCCC" stroke-width="2" fill="none"/>
              </svg>
              <input
                type="password"
                placeholder="密码"
                v-model="form.password"
                class="form-input"
              />
            </div>
          </div>
        </div>

        <!-- 手机号登录 -->
        <div v-if="loginType === 'phone'" class="form-fields">
          <div class="input-group">
            <div class="input-wrapper">
              <svg class="input-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">
                <rect x="5" y="2" width="10" height="16" rx="2" fill="#CCCCCC"/>
                <circle cx="10" cy="15" r="1" fill="white"/>
              </svg>
              <input
                type="tel"
                placeholder="手机号"
                v-model="form.phone"
                class="form-input"
              />
            </div>
          </div>
          <div class="input-group verification-group">
            <div class="input-wrapper verification-input">
              <svg class="input-icon" width="20" height="20" viewBox="0 0 20 20" fill="none">
                <rect x="2" y="6" width="16" height="10" rx="2" fill="#CCCCCC"/>
                <path d="M6 6V4C6 2.89543 6.89543 2 8 2H12C13.1046 2 14 2.89543 14 4V6" stroke="#CCCCCC" stroke-width="2" fill="none"/>
              </svg>
              <input
                type="text"
                placeholder="验证码"
                v-model="form.verificationCode"
                class="form-input"
              />
            </div>
            <button
              type="button"
              class="verification-btn"
              @click="getVerificationCode"
              :disabled="verificationCountdown > 0"
            >
              {{ verificationCountdown > 0 ? `${verificationCountdown}s` : '获取验证码' }}
            </button>
          </div>
        </div>

        <!-- 选项 -->
        <div class="form-options">
          <label class="checkbox-wrapper">
            <input type="checkbox" v-model="form.rememberMe" />
            <span class="checkmark"></span>
            7天内自动登录
          </label>
          <a href="javascript:void(0)" class="forgot-password" @click="openForgotDialog">忘记密码</a>
        </div>

        <!-- 登录按钮 -->
        <button type="submit" class="login-button" :disabled="!canLogin || loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
    </div>
  </div>

  <!-- 忘记密码对话框 -->
  <el-dialog v-model="forgotVisible" title="找回密码" width="420px" append-to-body>
    <div class="forgot-form">
      <div class="form-row">
        <label>手机号</label>
        <input v-model="forgot.phone" placeholder="请输入手机号" class="form-input" />
      </div>
      <div class="form-row" style="display:flex; gap:10px; align-items:center;">
        <div style="flex:1">
          <input v-model="forgot.code" placeholder="短信验证码" class="form-input" />
        </div>
        <button type="button" class="verification-btn" :disabled="forgotCountdown>0" @click="sendForgotCode">
          {{ forgotCountdown>0 ? `${forgotCountdown}s` : '获取验证码' }}
        </button>
      </div>
      <div class="form-row">
        <label>新密码</label>
        <input type="password" v-model="forgot.password" placeholder="请输入新密码(≥6位)" class="form-input" />
      </div>
      <div class="form-row">
        <label>确认密码</label>
        <input type="password" v-model="forgot.confirm" placeholder="请再次输入新密码" class="form-input" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="forgotVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitResetPassword">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import http from '@/api/http'
import { ElMessage } from 'element-plus'
export default {
  name: 'Login',
  data() {
    return {
      loginType: 'account', // 'account' 或 'phone'
      form: {
        username: '',
        password: '',
        phone: '',
        verificationCode: '',
        rememberMe: false
      },
      verificationCountdown: 0,
      countdownTimer: null,
      loading: false,
      // 忘记密码对话框
      forgotVisible: false,
      forgot: {
        phone: '',
        code: '',
        password: '',
        confirm: '',
      },
      forgotCountdown: 0,
      forgotTimer: null,
    }
  },
  computed: {
    canLogin() {
      if (this.loginType === 'account') {
        const u = (this.form.username || '').trim()
        const p = this.form.password || ''
        return u.length >= 3 && p.length >= 6
      } else {
        const phone = (this.form.phone || '').trim()
        const code = (this.form.verificationCode || '').trim()
        const phoneOk = /^1[3-9]\d{9}$/.test(phone)
        const codeOk = code.length >= 4 && code.length <= 6
        return phoneOk && codeOk
      }
    },
  },
  methods: {
    openForgotDialog() {
      this.forgotVisible = true
      // 预填手机号（如用户已输入）
      this.forgot.phone = (this.form.phone || '').trim()
    },
    async sendForgotCode() {
      if (this.forgotCountdown > 0) return
      const phone = (this.forgot.phone || '').trim()
      if (!phone) return ElMessage.warning('请输入手机号')
      if (!/^1[3-9]\d{9}$/.test(phone)) return ElMessage.error('请输入合法的中国大陆手机号')
      try {
        const res = await http.post('/intelligent-login/login/send-code', { phone }, { showError: false })
        const body = res?.data || {}
        const ok = body?.success === true || body?.code === 0 || body?.code === 200
        const msg = body?.message || body?.msg || '验证码已发送'
        if (!ok) throw new Error(msg)
        ElMessage.success(msg)
        this.forgotCountdown = 60
        if (this.forgotTimer) clearInterval(this.forgotTimer)
        this.forgotTimer = setInterval(() => {
          this.forgotCountdown--
          if (this.forgotCountdown <= 0) clearInterval(this.forgotTimer)
        }, 1000)
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || e.message || '验证码发送失败')
      }
    },
    async submitResetPassword() {
      const phone = (this.forgot.phone || '').trim()
      const code = (this.forgot.code || '').trim()
      const pwd = this.forgot.password || ''
      const confirm = this.forgot.confirm || ''
      if (!/^1[3-9]\d{9}$/.test(phone)) return ElMessage.error('请输入合法的中国大陆手机号')
      if (!code) return ElMessage.error('请输入验证码')
      if (pwd.length < 6) return ElMessage.error('新密码长度至少 6 位')
      if (pwd !== confirm) return ElMessage.error('两次输入的密码不一致')
      try {
        // 1) 提前验证身份：用短信验证码完成一次手机号登录校验（不做跳转/不存储token）
        const verifyRes = await http.post('/intelligent-login/login/phoneLogin', { phone, code }, { showError: false })
        const verifyBody = verifyRes?.data || {}
        const verifyOk = verifyBody?.success === true || verifyBody?.code === 0 || verifyBody?.code === 200
        if (!verifyOk) throw new Error(verifyBody?.message || verifyBody?.msg || '身份验证失败，请重试')
        // 不存储任何用户信息/权限/token（如后端返回token也忽略）

        // 2) 调用修改密码接口
        const resetRes = await http.post('/intelligent-login/login/updatePsaaword', { phone, newPassword: pwd }, { showError: false })
        const resetBody = resetRes?.data || {}
        const resetOk = resetBody?.success === true || resetBody?.code === 0 || resetBody?.code === 200
        if (!resetOk) throw new Error(resetBody?.message || resetBody?.msg || '密码修改失败')

        ElMessage.success('密码重置成功，请使用新密码登录')
        this.forgotVisible = false
        // 清理对话框字段
        this.forgot = { phone: '', code: '', password: '', confirm: '' }
        this.forgotCountdown = 0
        if (this.forgotTimer) clearInterval(this.forgotTimer)
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || e.message || '重置失败')
      }
    },
    switchLoginType(type) {
      this.loginType = type
      // 清空表单
      this.form = {
        username: '',
        password: '',
        phone: '',
        verificationCode: '',
        rememberMe: this.form.rememberMe
      }
    },
    async getVerificationCode() {
      if (this.verificationCountdown > 0) return
      const phone = (this.form.phone || '').trim()
      if (!phone) {
        ElMessage.warning('请输入手机号')
        return
      }
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        ElMessage.error('请输入合法的中国大陆手机号')
        return
      }
      try {
        // 发送验证码
        const res = await http.post('/intelligent-login/login/send-code', { phone }, { showError: false })
        const body = res?.data || {}
        const ok = body?.success === true || body?.code === 0 || body?.code === 200
        const msg = body?.message || body?.msg || '验证码发送成功'
        if (!ok) throw new Error(msg)
        ElMessage.success(msg)
        // 成功后启动倒计时
        this.verificationCountdown = 60
        if (this.countdownTimer) clearInterval(this.countdownTimer)
        this.countdownTimer = setInterval(() => {
          this.verificationCountdown--
          if (this.verificationCountdown <= 0) {
            clearInterval(this.countdownTimer)
          }
        }, 1000)
      } catch (err) {
        ElMessage.error(err?.response?.data?.message || err.message || '验证码发送失败')
      }
    },
    validateAccount() {
      const u = (this.form.username || '').trim()
      const p = this.form.password || ''
      if (!u) return '请输入账号'
      if (u.length < 3) return '账号长度至少 3 位'
      if (!p) return '请输入密码'
      if (p.length < 6) return '密码长度至少 6 位'
      if (/\s/.test(u)) return '账号不能包含空格'
      return ''
    },
    validatePhone() {
      const phone = (this.form.phone || '').trim()
      const code = (this.form.verificationCode || '').trim()
      if (!phone) return '请输入手机号'
      if (!/^1[3-9]\d{9}$/.test(phone)) return '请输入合法的中国大陆手机号'
      if (!code) return '请输入验证码'
      if (code.length < 4 || code.length > 6) return '验证码长度应为 4-6 位'
      return ''
    },
    async handleLogin() {
      if (this.loading) return
      try {
        // 前端表单校验
        if (this.loginType === 'account') {
          const msg = this.validateAccount()
          if (msg) {
            ElMessage.error(msg)
            return
          }
        } else {
          const msg = this.validatePhone()
          if (msg) {
            ElMessage.error(msg)
            return
          }
        }

        this.loading = true
        if (this.loginType === 'account') {
          const payload = {
            username: this.form.username.trim(),
            password: this.form.password,
          }
          const res = await http.post('/intelligent-login/login', payload, { showError: false })
          const body = res?.data || {}
          const token = body?.token || body?.data?.token
          const httpOk = res && res.status >= 200 && res.status < 300
          const bizOk = body?.code === 0 || body?.code === 200 || body?.success === true || body?.data || token
          if (!(httpOk && (bizOk && token))) {
            throw new Error(body?.message || '登录失败：接口未返回有效 token')
          }
          if (this.form.rememberMe) {
            localStorage.setItem('token', token)
          } else {
            sessionStorage.setItem('token', token)
          }
          localStorage.removeItem('userInfo')
          sessionStorage.removeItem('userInfo')
          localStorage.removeItem('permissions')
          sessionStorage.removeItem('permissions')
          ElMessage.success('登录成功')
          const redirect = this.$route.query.redirect || '/dashboard'
          this.$router.push(redirect)
        } else {
          const payload = {
            phone: (this.form.phone || '').trim(),
            code: (this.form.verificationCode || '').trim(),
          }
          const res = await http.post('/intelligent-login/login/phoneLogin', payload, { showError: false })
          const body = res?.data || {}
          const token = body?.token || body?.data?.token
          const httpOk = res && res.status >= 200 && res.status < 300
          const bizOk = body?.code === 0 || body?.code === 200 || body?.success === true || body?.data || token
          if (!(httpOk && (bizOk && token))) {
            throw new Error(body?.message || '登录失败：接口未返回有效 token')
          }
          if (this.form.rememberMe) {
            localStorage.setItem('token', token)
          } else {
            sessionStorage.setItem('token', token)
          }
          localStorage.removeItem('userInfo')
          sessionStorage.removeItem('userInfo')
          localStorage.removeItem('permissions')
          sessionStorage.removeItem('permissions')
          ElMessage.success('登录成功')
          const redirect = this.$route.query.redirect || '/dashboard'
          this.$router.push(redirect)
        }
      } catch (err) {
        console.error('登录失败:', err)
        ElMessage.error(err?.response?.data?.message || err.message || '登录失败')
      } finally {
        this.loading = false
      }
    }
  },
  beforeUnmount() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
    if (this.forgotTimer) {
      clearInterval(this.forgotTimer)
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 20px;
  padding: 60px 50px;
  width: 100%;
  max-width: 480px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  margin-bottom: 20px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.login-tabs {
  display: flex;
  margin-bottom: 40px;
  border-bottom: 1px solid #f0f0f0;
}

.tab-button {
  flex: 1;
  padding: 15px 0;
  border: none;
  background: none;
  font-size: 16px;
  color: #999;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.tab-button.active {
  color: #2196F3;
  font-weight: 500;
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #2196F3;
}

.form-fields {
  margin-bottom: 30px;
}

.input-group {
  margin-bottom: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 15px;
  z-index: 1;
}

.form-input {
  width: 100%;
  padding: 15px 15px 15px 50px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #2196F3;
}

.form-input::placeholder {
  color: #ccc;
}

.verification-group {
  display: flex;
  gap: 10px;
}

.verification-input {
  flex: 1;
}

.verification-btn {
  padding: 15px 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.verification-btn:hover:not(:disabled) {
  border-color: #2196F3;
  color: #2196F3;
}

.verification-btn:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-wrapper input[type="checkbox"] {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-wrapper input[type="checkbox"]:checked + .checkmark {
  background: #2196F3;
  border-color: #2196F3;
}

.checkbox-wrapper input[type="checkbox"]:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 5px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.forgot-password {
  color: #2196F3;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 15px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.login-button:hover:not(:disabled) {
  background: #1976D2;
}

.login-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>
